package com.bwc.coze

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import com.google.gson.JsonParser
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import java.io.IOException

class MainActivity : AppCompatActivity() {
    private var btnSubmit  : Button ?= null
    private var ed_input_text : TextView ?= null
    private var ed_stream : TextView ?= null

    //客户端id  50311028422963954880554412003768.app.coze
    private val apiToken = "Bearer pat_l3HqFPSGGKzviXPB0kcWgCn9A66NwmjpAzaixWBba7SikeGuknzm0dnU3yfSR19c"
    private val botId = "7514124054191390757"
    private val client = OkHttpClient()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        btnSubmit  = findViewById(R.id.btn_tijiao)
        ed_input_text = findViewById(R.id.ed_input_text)
        ed_stream = findViewById(R.id.ed_stream)
        btnSubmit?.setOnClickListener {
            val queryText = ed_input_text?.text.toString()
            sendQueryToCoze(queryText) { reply ->
                runOnUiThread {
                    ed_stream?.setText(reply)
                }
            }
        }

    }

    private fun sendQueryToCoze(query: String, callback: (String) -> Unit) {
        val url = "https://api.coze.cn/open_api/v2/chat"

        val json = """
            {
              "bot_id": "$botId",
              "user": "android_user_1",
              "query": "$query",
              "stream": false
            }
        """.trimIndent()

        val body = RequestBody.create(
            "application/json; charset=utf-8".toMediaTypeOrNull(), json
        )

        val request = Request.Builder()
            .url(url)
            .post(body)
            .addHeader("Authorization", apiToken)
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.e("CozeAPI", "Request failed: ${e.message}")
                callback("请求失败：${e.message}")
            }

            override fun onResponse(call: Call, response: Response) {
                val resBody = response.body?.string()
                if (response.isSuccessful && resBody != null) {
                    try {
                        val jsonObj = JsonParser.parseString(resBody).asJsonObject
                        val messages = jsonObj["messages"]?.asJsonArray
                        Log.d("jsonObj---", "onResponse: $messages")
                        Log.d("jsonObj---", "onResponse: $jsonObj")
                        val content = messages?.firstOrNull()
                            ?.asJsonObject?.get("content")?.asString ?: "无内容"

                        callback(content)
                    } catch (e: Exception) {
                        callback("解析失败")
                    }
                } else {
                    callback("API 错误: ${response.code}")
                }
            }
        })
    }
}